//
//  ESCommentViewController.m
//  Eyeshot
//
//  Created by admin on 15/7/8.
//  Copyright (c) 2015年 eyeshot. All rights reserved.
//

#import "ESCommentViewController.h"
#import "ESDuanziTableCell.h"
#import "ESTitleView.h"
#import "ESComment.h"
#import "ESCommentCell.h"
#import "ESCommentBar.h"

typedef CGFloat(^TopicMaxY)(void);

@interface ESCommentViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
@property (nonatomic, strong) NSMutableArray *models;
@property (nonatomic, weak) UITableView *tableView;
@property (nonatomic, weak) ESCommentBar *buttomBar;
@property (nonatomic, weak) ESCommentBar *topBar;
@property (nonatomic, weak) UIControl *cover;
@property (nonatomic, strong) TopicMaxY topicMaxY;
@property(nonatomic,assign)ESRefreshType refreshType;
@property(nonatomic,assign)NSInteger page;
@property(nonatomic,assign)NSInteger total;
@end

@implementation ESCommentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _refreshType = ESRefreshNew;
    _page = 1;
    
    // Do any additional setup after loading the view.
    //添加中间的标题titleView
    ESTitleView *titleView = [[ESTitleView alloc] init];
    titleView.width = 20 * kHorizen;
    titleView.height = 7 * kVertical;
    titleView.title = @"评论";
    self.navigationItem.titleView = titleView;
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self configTableView];
    [self configCommentBar];
    [self requestData];
    
}

- (void)configTableView {
    UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    tableView.height = self.view.height - 10 * kVertical - BAR_HEIGHT; //tableView的高度需要减去CommentBar的高度
    tableView.dataSource = self;
    tableView.delegate = self;
    [self.view addSubview:tableView];
    _tableView = tableView;
    _tableView.backgroundColor = ESColor(234, 234, 234);
    [_tableView registerClass:[ESCommentCell class] forCellReuseIdentifier:@"CommentCell"];
    [_tableView registerClass:[ESDuanziTableCell class] forCellReuseIdentifier:@"DuanziCell"];
    _models = [NSMutableArray array];
    
    [_tableView addLegendHeaderWithRefreshingBlock:^{
        [self loadNewData];
    }];
    
    [_tableView addLegendFooterWithRefreshingBlock:^{
        [self loadMoreData];
    }];
    
    
}

- (void)configInputBar {
    NSLog(@"%@",NSStringFromCGRect(self.view.frame));
    UITextField *buttomField = [[UITextField alloc] initWithFrame:CGRectMake(8 * kHorizen, SCREEN_HEIGHT - 6 * kVertical - BAR_HEIGHT, SCREEN_WIDTH - 16 * kHorizen, 6 * kVertical)];
    buttomField.borderStyle = UITextBorderStyleRoundedRect;
    buttomField.placeholder = @"写评论...";
    [self.view addSubview:buttomField];
    
    UITextField *topField = [[UITextField alloc] initWithFrame:CGRectMake(8 * kHorizen, 0, SCREEN_WIDTH - 16 * kHorizen, 6 * kVertical)];
    topField.borderStyle = UITextBorderStyleRoundedRect;
    buttomField.inputAccessoryView = topField;
    
}

#pragma mark - MJRefresh
- (void)loadNewData {
    _refreshType = ESRefreshNew;
    [self requestData];
    
}

- (void)loadMoreData {
    _refreshType = ESRefreshMore;
    _page+=1;
    
    if (_page <= ceil(_total / 20.0)) {
        [self requestData];
    }else {
        [self.tableView.footer setTitle:@"" forState:(MJRefreshFooterStateIdle)];
        [self.tableView.footer endRefreshing];
    }
    
    
}


#pragma mark - 网络请求

- (void)requestData {
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    
    NSString *page = [NSString stringWithFormat:@"%ld",_page];
    
    NSString *reqStr = @"http://api.budejie.com/api/api_open.php";
    NSDictionary *reqParas = @{@"a": @"dataList",
                               @"appname": @"baisishequ",
                               @"asid": @"5E6124E7-C271-4F3F-9FE6-33E54108A2F3",
                               @"c": @"comment",
                               @"client": @"iphone",
                               @"data_id": _model.ID,
                               @"device": @"iPhone4S",
                               @"hot": @"1",
                               @"jbk": @"0",
                               @"mac": @"",
                               @"market": @"",
                               @"openudid": @"915b9db78a08fe308fdeda8a949ba0f436c6be8f",
                               @"page": page,
                               @"per": @"50",
                               @"udid": @"",
                               @"uid": @"15150267",
                               @"ver": @"3.6"
                               };
    [mgr GET:reqStr parameters:reqParas success:^(AFHTTPRequestOperation *operation, NSDictionary *responseObject) {
        
        
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            _total = [[responseObject objectForKey:@"total"] integerValue];
            NSArray *responseArray = [responseObject objectForKey:@"data"];
            
            if (responseArray.count > 0) {
                if (_refreshType == ESRefreshNew) {
                    [_models removeAllObjects];
                }
                
                for (NSDictionary *dict in responseArray) {
                    
                    ESComment *model = [ESComment objectWithKeyValues:dict];
                    BOOL isUnique = YES;
                    for (ESComment *m in _models) {
                        if ([m.comment_id isEqualToString:model.comment_id]) {
                            isUnique = NO;
                            break;
                            }
                    }
                    if (isUnique) {
                        [_models addObject:model];
                    }
                }
                
                [self.tableView reloadData];
                
                
                if (_refreshType == ESRefreshNew) {
                    CGFloat footerH = self.tableView.footer.height;
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(500 * NSEC_PER_MSEC)), dispatch_get_main_queue(), ^{
                        [self.tableView scrollRectToVisible:CGRectMake(0, _topicMaxY(), SCREEN_WIDTH, SCREEN_HEIGHT - 10 * kVertical - BAR_HEIGHT - footerH) animated:YES];
                    });
                    
//                    [_buttomBar.middleField becomeFirstResponder];
//                    [_buttomBar textMode];
                }
                
            }
        }
        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        ESLog(@"%@",error);
    }];
}


#pragma mark - 评论Bar
- (void)configCommentBar {
    ESCommentBar *buttomBar = [[ESCommentBar alloc] init];
    buttomBar.x = ZERO;
    buttomBar.y = SCREEN_HEIGHT - BAR_HEIGHT - buttomBar.height;
    buttomBar.middleField.delegate = self;
    [buttomBar textMode];
    [self.view addSubview:buttomBar];
    _buttomBar = buttomBar;
    
    ESCommentBar *topBar = [[ESCommentBar alloc] init];
    [topBar textMode];
    buttomBar.middleField.inputAccessoryView = topBar;
    _topBar = topBar;
    
    [buttomBar.keyBoardBtn addTarget:self action:@selector(clickKeyBoard:) forControlEvents:UIControlEventTouchUpInside];
    [buttomBar.voiceBtn addTarget:self action:@selector(clickVoice:) forControlEvents:UIControlEventTouchUpInside];
    [topBar.voiceBtn addTarget:self action:@selector(clickTopVoice:) forControlEvents:UIControlEventTouchUpInside];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHidden:) name:UIKeyboardWillHideNotification object:nil];
    
}

- (void)clickVoice:(UIButton *)btn {
    [_buttomBar voiceMode];
}

- (void)clickKeyBoard:(UIButton *)btn {
    [_buttomBar.middleField becomeFirstResponder];
    [_topBar.middleField becomeFirstResponder];
}

- (void)clickTopVoice:(UIButton *)btn {
    [self passText];
    [self.view endEditing:YES];
    [self.view endEditing:YES];
    
   
}


- (void)passText {
    NSString *text = _topBar.middleField.text;
    if (text.length) {
        _buttomBar.middleField.text = text;
        [_buttomBar textMode];
    }else {
        [_buttomBar voiceMode];
    }
}

- (void)keyboardWillShow:(NSNotification *)aNotification
{
    [_topBar.middleField becomeFirstResponder];
}

- (void)keyboardWillHidden:(NSNotification *)aNotification
{
    
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self passText];
    [self.view endEditing:YES];
    [self.view endEditing:YES];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    if (section == 0) {
        return 1;
    }else {
        return _models.count;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return [ESDuanziTableCell heightForCellWithModel:_model];
    } else {
        return [ESCommentCell heightForCellWithModel:_models[indexPath.row]];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        ESDuanziTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DuanziCell"];
        cell.model = _model;
        _topicMaxY = ^ {
            return CGRectGetMaxY(cell.frame);
        };
        return cell;
    } else {
        ESCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CommentCell"];
        cell.model = _models[indexPath.row];
        return cell;
    }
    
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        
        return @"最新评论";
    }
    return nil;
}

- (void)viewWillDisappear:(BOOL)animated {
    [self.view endEditing:YES];
}

@end
